package com.ushine.web.template.transactional.facade.impl;

import com.ushine.web.component.exception.ServiceException;
import com.ushine.web.template.transactional.facade.ITransactionFacade;
import com.ushine.web.template.transactional.model.FirstTransactionDO;
import com.ushine.web.template.transactional.model.SecondTransactionDO;
import com.ushine.web.template.transactional.service.IFirstTransactionService;
import com.ushine.web.template.transactional.service.ISecondTransactionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * @Author: yls
 * @Date 2022/2/14 11:22
 * @Description: 包装层service
 * @Version 1.0
 **/
@Slf4j
@Service
public class TransactionFacadeImpl implements ITransactionFacade {

    @Resource
    private IFirstTransactionService firstTransactionService;

    @Resource
    private ISecondTransactionService secondTransactionService;

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void insetFirstAndSecondException(FirstTransactionDO firstTransaction, SecondTransactionDO secondTransaction) throws ServiceException {
        /*
         * 涉及图片保存、redis其他操作，均先保存数据库记录，然后再做其他操作、
         * 这样才能保证其他操作出现异常，数据库信息能够自动回滚
         */
        firstTransactionService.insert(firstTransaction);
        secondTransactionService.insertByException(secondTransaction);
        /*
         * 其他业务处理：一定要放到数据库操作之后
         */
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void insetFirstAndSecond(FirstTransactionDO firstTransaction, SecondTransactionDO secondTransaction) {
        firstTransactionService.insert(firstTransaction);
        secondTransactionService.insert(secondTransaction);
    }


    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void insetNestedException(FirstTransactionDO firstTransaction, SecondTransactionDO secondTransaction)
            throws ServiceException {
        /*
         * 涉及图片保存、redis其他操作，均先保存数据库记录，然后再做其他操作、
         * 这样才能保证其他操作出现异常，数据库信息能够自动回滚
         */
        firstTransactionService.insert(firstTransaction);
        secondTransactionService.insertNestedByException(secondTransaction);
        /*
         * 其他业务处理：一定要放到数据库操作之后
         */
    }

}
